package com.ganeshkrishnan.globald.web.controller;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ganeshkrishnan.globald.dao.CountryManagerDao;
import com.ganeshkrishnan.globald.dao.PersonDao;
import com.ganeshkrishnan.globald.model.CountryDetail;
import com.ganeshkrishnan.globald.model.Person;
import com.ganeshkrishnan.globald.model.PersonLocation;
import com.ganeshkrishnan.globald.web.utils.Constants;

@Controller
@RequestMapping("/location")
public class LocationController {
	protected final Log			logger	= LogFactory.getLog(getClass());
	@Autowired
	private CountryManagerDao	countryManagerdao;
	@Autowired
	private PersonDao			personDao;

	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	public CountryManagerDao getCountryManager() {
		return countryManagerdao;
	}

	public void setCountryManager(CountryManagerDao countryManagerdao) {
		this.countryManagerdao = countryManagerdao;
	}

	public LocationController() {
	}

	@RequestMapping(method = RequestMethod.GET)
	public String redir() {
		return "redirect:/resource.html";
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String storeLocation(@RequestParam String cCode, @RequestParam float lat, @RequestParam float lon,
			Model model, HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		Long personID = (Long) session.getAttribute("personID");
		if (null == personID) {
			return "redirect:/country.html";
		}
		Person person = personDao.get(personID);
		CountryDetail cd = countryManagerdao.findByCountryCode(cCode);
		//If either the person doesn't exist or the country is invalid then return back to country selection
		if (null == person || null == cd) {
			return "redirect:/country.html";
		}
		person.setCountryCode(cd);
		Set<PersonLocation> locations = new HashSet<PersonLocation>();
		PersonLocation pl = new PersonLocation();
		pl.setLocationType(Constants.LocationType.HOME.ordinal());
		pl.setLatitude(lat);
		pl.setLongitude(lon);
		pl.setDateCreated(new Date());
		pl.setPerson(person);
		locations.add(pl);
		person.setLocation(locations);
		personDao.save(person);
		return "redirect:/resource.html";
	}
}